package br.com.fixtrader.quoteserver;

import java.util.LinkedList;

public class ThreadPool {
	private LinkedList<Runnable> tasks = new LinkedList<Runnable>();
	
	public ThreadPool(int numberOfThreads) {
		for (int i = 0 ; i < numberOfThreads ; i++) {
			Thread t = new Worker(this);
			t.start();
		}
	}

	public void run(Runnable task) {
		synchronized (tasks) {
			tasks.addLast(task);
			tasks.notify();
		}
	}

	public Runnable getNext() {
		Runnable returnVal = null;
		synchronized (tasks) {
			while (tasks.isEmpty()) {
				try {
					tasks.wait();
				} catch (InterruptedException ex) {
					System.err.println("Interrupted");
				}
			}
			returnVal = (Runnable) tasks.removeFirst();
		}
		return returnVal;
	}

}
